package com.ysw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysw.bean.FileExport;
import com.ysw.service.FileExportService;
import com.ysw.mapper.FileExportMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author ysw
 * @description 针对表【file_export】的数据库操作Service实现
 * @createDate 2023-04-25 16:40:23
 */
@Service
public class FileExportServiceImpl extends ServiceImpl<FileExportMapper, FileExport>
        implements FileExportService {
    @Autowired
    private FileExportMapper fileExportMapper;
    static ThreadPoolExecutor executor =
            new ThreadPoolExecutor(10, 10, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    public void export(HttpServletResponse response, int count, int limit) {
        int extraPage = count % limit > 0 ? 1 : 0;
        int pageNumCount = count / limit + extraPage;
        CountDownLatch countDownLatch = new CountDownLatch(pageNumCount);
        List<CallTask> futureTasks = new ArrayList<>();
        for (int i = 0; i < pageNumCount; i++) {
            futureTasks.add(new CallTask(countDownLatch, fileExportMapper, i * limit, limit));
        }
        List<Future<List<FileExport>>> futures = new ArrayList<>();
        try {
            futures = executor.invokeAll(futureTasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (Future<List<FileExport>> future : futures) {
            try {
                List<FileExport> fileExports = future.get();
                System.out.println(fileExports.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

    }

    @Data
    @AllArgsConstructor
    class CallTask implements Callable<List<FileExport>> {
        CountDownLatch countDownLatch;
        FileExportMapper fileExportMapper;
        int start;
        int pageSize;

        @Override
        public List<FileExport> call() throws Exception {
            List<FileExport> fileExports =
                    fileExportMapper.selectList(new LambdaQueryWrapper<>(FileExport.class).last(String.format("limit %s,%s", start, pageSize)));
            countDownLatch.countDown();
            System.out.println(fileExports.get(fileExports.size()-1));
            return fileExports;
        }
    }
}




